﻿using System;
using System.Data;
using System.Diagnostics;

namespace HQS.TokenInterpolation
{
    internal static class LogicalExpressionParser
    {
        private static readonly DataTable dataTable = new DataTable();

        public static ParserResult<bool?> Parse(string expression)
        {
            ParserResult<bool?> result = null;
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            Stopwatch processingWatch = Stopwatch.StartNew();
            try
            {
                object exp = dataTable.Compute(expression.Replace("==", "="), null);
                bool boolValue;
                bool? resultBoolValue = null;
                if (exp != null && bool.TryParse(exp.ToString(), out boolValue))
                {
                    resultBoolValue = boolValue;
                }

                string errorMessage = null;
                if (resultBoolValue.HasValue == false)
                {
                    errorMessage = string.Format("The following expression \"{0}\" didn't evaluate right", expression);
                }

                result = new ParserResult<bool?>(resultBoolValue);
                if (string.IsNullOrWhiteSpace(errorMessage) == false)
                {
                    result.AddErrorMessage(errorMessage);
                }
            }
            catch (Exception e)
            {
                result = new ParserResult<bool?>(null);
                result.AddErrorMessage(e.Message);
            }
            finally
            {
                processingWatch.Stop();
            }

            return result;
        }
    }
}